package tt.dz.egobus.servicemanager.business.distance;

import tt.dz.egobus.base.context.SpringApplicationHolder;
import tt.dz.egobus.servicemanager.bean.BusinessCode;
import tt.dz.egobus.servicemanager.bean.SpringConfigConstant;
import tt.dz.egobus.servicemanager.business.point.Point;
import tt.dz.egobus.servicemanager.business.point.PointAlgorithmHelp;


/**
 * @author Anson
 * @date 17-3-30
 * @name 单次服务的最大距离控制
 * @since 1.0.3
 */
public class SingleServiceMaxOverAlgorithm implements MaxOverAlgorithm {

    private static final BusinessCode BUSINESS_CODE = BusinessCode.TIME;

    private static final String ID = String.valueOf(BUSINESS_CODE.getCode());
    //尽量不要在静态方法中处理当前实例获取，可能会spring未加载完全导致了空指针异常
    private SpringConfigConstant springConfigConstant;

    private volatile boolean isLoaded = false;

    @Override
    public String id() {
        return ID;
    }

    @Override
    public int businessCode() {
        return BUSINESS_CODE.getCode();
    }

    /**
     * @author Anson
     * @date 17-3-30
     * @name 根据配置文件中配置项business.distance.single.max, 来控制
     * @see PointAlgorithmHelp#getDistance(Point, Point)
     * @see SpringConfigConstant#getSingleMax()
     * @since 1.0.3
     */
    @Override
    public boolean isOverMaxDistance(Point startPoint, Point endPoint) {
        this.init();
        int singleMax = springConfigConstant.getSingleMax();
        double length = PointAlgorithmHelp.getDistance(startPoint, endPoint);
        return length > singleMax;
    }

    @Override
    public double maxDistance() {
        this.init();
        int singleMax = springConfigConstant.getSingleMax();
        return singleMax;
    }

    private void init() {
        if (this.isLoaded) {
            return;
        }
        this.springConfigConstant = SpringApplicationHolder.getBean("springConfigConstant", SpringConfigConstant.class);
        this.isLoaded = true;
    }
}
